package com.enqualcomm.kids.mvp.terminalbill;

import android.content.Context;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.bean.AbstractorMessage;
import com.enqualcomm.kids.bean.TerminalBillMessage;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.network.socket.response.AllBillResult;
import com.enqualcomm.kids.network.socket.response.GetQuerySIMInfoWayResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.view.dialog.DeleteBillMessageCallBack;
import com.enqualcomm.kids.view.dialog.DeleteBillMessageDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import common.utils.GsonFactory;
import common.utils.MyLogger;

/**
 * Created by Sunzhigang on 2015/11/2.
 */
public class BillPresenter implements ICheckBillHandler, DeleteBillMessageCallBack {

    private AppDefault appDefault;
    private Context context;

    BillDBManager dbManager;

    private String userterminalid;
    private String terminalid;
    private ICheckBillModel model;
    private ICheckBillView view;
    private ISetCheckBillView setView;
    /**
     * 发送获取话费流量消息的个数
     */
    private int mSendCmdCount = 0;
    /**
     * 用于不断从服务器获取定时器
     */
    private Timer timer;
    private List<TerminalBillMessage> billMessageList = new ArrayList<>();
    //    private List<String> jsonMessageList = new ArrayList<>();
    private List<TerminalBillMessage> billMessages = new ArrayList<>();


    private boolean isShowNoMessagebg = false;
    private String notice_send_str_1;
    private String notice_send_str_0;

    public BillPresenter(Context context, String terminalid, String userterminalid) {
        model = new CheckBillModel();

        this.terminalid = terminalid;
        this.userterminalid = userterminalid;
        this.appDefault = new AppDefault();
        this.context = context;

        dbManager = new BillDBManager(context, appDefault.getUserid());

    }

    public void attachView(ICheckBillView view) {
        this.view = view;
        getHistoryBillMessageFromDB();

        UserTerminalDefault userTerminalDefault = new UserTerminalDefault(userterminalid);
        QueryUserTerminalInfoResult.Data terminalInfo = userTerminalDefault.getInfo();
        notice_send_str_0 = context.getString(R.string.checkbill_notice_1);
        notice_send_str_1 = context.getString(R.string.checkbill_notice_2);
//        model.getCheckBillResult(appDefault.getUserkey(), appDefault.getUserid()
//                , terminalid, BillPresenter.this);
    }

    public void attachSetView(ISetCheckBillView setView) {
        this.setView = setView;
    }

    public void dettachView() {
        this.view = null;

    }

    public void dettachSetView() {
        this.setView = null;
    }

    public void checkTermianlBill(int traffic) {
        if (mSendCmdCount == 2) {
            if (view != null) {
                view.showMessage();
            }
        } else {
            model.sendCheckbillCmd(appDefault.getUserkey(), appDefault.getUserid(),
                    terminalid, appDefault.getUsername(), traffic, this);
        }
    }

    public void deleteAllMessage() {
        if (billMessages.size() == 0) {
            return;
        }
        new DeleteBillMessageDialog(context, true, 0, this).show();
    }

    @Override
    public void onSendSuccess(int traffic) {
        TerminalBillMessage message = new TerminalBillMessage();
        message.message = traffic == 1 ? notice_send_str_1 : notice_send_str_0;
        message.time = System.currentTimeMillis();
        /**将消息添加到-billMessages*/
        billMessages.add(message);
        MyLogger.kLog().i("billMessages=======================" + billMessages.size());
        if (isShowNoMessagebg) {
            if (view != null) {
                view.showNoMessageBackground(false);
            }
            isShowNoMessagebg = false;
        }

        if (view != null) {
            sort(billMessages);
//            processDate();
            view.notifyAdapterDataChange(billMessages);
        }
        if (mSendCmdCount == 0) {
            timer = new Timer("getterminaltimer");
        }
        mSendCmdCount++;
        //TODO
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                model.getCheckBillResult(appDefault.getUserkey(), appDefault.getUserid()
                        , terminalid, BillPresenter.this);
            }
        }, 1000, 10 * 1000);

    }

    @Override
    public void onGetSuccess(AllBillResult response) {
        TerminalBillMessage message;
        if (response.result.sms.size() == 1) {
            for (int i = 0; i < billMessages.size(); i++) {
                message = billMessages.get(i);
                if (!isAutoCheckBill(message)) {
                    message.message = response.result.sms.get(0).smsbody;
                    billMessageList.add(message);
                    break;
                } else if (i == billMessages.size() - 1 && isAutoCheckBill(message)) {
                    TerminalBillMessage billBean = new TerminalBillMessage();
                    billBean.message = response.result.sms.get(0).smsbody;
                    billBean.time = System.currentTimeMillis();
                    billMessages.add(billBean);
                }
            }
            mSendCmdCount--;
        }

        if (response.result.sms.size() == 2) {
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < billMessages.size(); j++) {
                    message = billMessages.get(i);
                    if (!isAutoCheckBill(message)) {
                        message.message = response.result.sms.get(i).smsbody;
                        billMessageList.add(message);
                        break;
                    } else if (i == billMessages.size() - 1 && isAutoCheckBill(message)) {
                        TerminalBillMessage billBean = new TerminalBillMessage();
                        billBean.message = response.result.sms.get(0).smsbody;
                        billBean.time = System.currentTimeMillis();
                        billMessages.add(billBean);
                    }
                }
            }
            mSendCmdCount = 0;
        }

        /**取消定时器*/
        if (mSendCmdCount == 0 && timer != null) {
            timer.cancel();
        }//TODO
        if (view != null && response.result.sms.size() != 0) {
            sort(billMessages);
            view.notifyAdapterDataChange(billMessages);
        }

    }


    @Override
    public void deleteBillMessage(boolean isToCleanAll, int position) {

        TerminalBillMessage message;
        String smsjson;

        if (isToCleanAll) {
            dbManager.deleteSMSFromDB(terminalid);
            billMessageList.clear();
            billMessages.clear();
        } else {
            billMessages.remove(position);
            String dJsonMessage = GsonFactory.newInstance().toJson(billMessages.get(position));
            dbManager.deleteSMSFromDB(terminalid, dJsonMessage);
        }
        if (view != null) {
            sort(billMessages);
            view.notifyAdapterDataChange(billMessages);
        }

    }


    void getHistoryBillMessageFromDB() {

        List<String> tList = dbManager.queryBillSMS(terminalid);
        billMessages = convertJsonToMessageBean(tList);

        if (billMessages.size() != 0) {
            if (view != null) {
                sort(billMessages);
                view.notifyAdapterDataChange(billMessages);
            }
        } else {
            isShowNoMessagebg = true;
            if (view != null) {
                view.showNoMessageBackground(isShowNoMessagebg);
            }
        }

    }


    public void onResume() {
        if (mSendCmdCount != 0) {
            timer = new Timer("getterminaltimer");
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    model.getCheckBillResult(appDefault.getUserkey(), appDefault.getUserid()
                            , terminalid, BillPresenter.this);
                }
            }, 1000, 10 * 1000);
        }
    }

    public void onStop() {
        List<String> tSMSList;
        if (timer != null) {
            timer.cancel();
        }
        tSMSList = convertMessageBeanToJson(billMessageList);
        dbManager.insertBillSMS(terminalid, tSMSList);
        /**应对从设置回来 billMessageList中有数据导致同一数据多次存入数据库*/
        billMessageList.clear();
        model.onStop();
    }


    public void getCheckBillSettings() {
        model.getCheckBillSettings(appDefault.getUserkey(), appDefault.getUserid(), terminalid, this);
    }

    public void setChecBillSettings() {
        model.setCheckBillSettings(appDefault.getUserkey(), appDefault.getUserid(), terminalid, setView.getCXLLsms(),
                setView.getCXYEsms(), setView.getHFCXNumber(), setView.getLLCXNumber(), this);
    }

    @Override
    public void getCheckBillSettingsSuccess(GetQuerySIMInfoWayResult result) {

        if (setView != null) {
            setView.showCheckBillSettings(result);
        }
    }

    @Override
    public void setCheckBillSettingsSuccess() {
        if (setView != null) {
            setView.showToast();
        }
    }

    private List<TerminalBillMessage> convertJsonToMessageBean(List<String> jsonList) {
        List<TerminalBillMessage> billMessages = new ArrayList<>();
        for (int i = 0; i < jsonList.size(); i++) {
            TerminalBillMessage bean = GsonFactory.newInstance().fromJson(jsonList.get(i), TerminalBillMessage.class);
            billMessages.add(bean);
        }
        jsonList.clear();
        return billMessages;
    }

    private List<String> convertMessageBeanToJson(List<TerminalBillMessage> beanList) {
        List<String> billJsonList = new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            String jsonBean = GsonFactory.newInstance().toJson(beanList.get(i));
            billJsonList.add(jsonBean);
        }
        return billJsonList;
    }

    private boolean isAutoCheckBill(TerminalBillMessage message) {
        return !(message.message.contains("您查询手表电话卡") || message.message.contains("Please wait for a monent") || message.message.contains("您查詢手錶電話卡"));
    }

    private static long getSecondsFromDate(String expireDate) {
        String[] split = expireDate.split("-");
        Calendar calendar = Calendar.getInstance();
        String year = expireDate.substring(0, 4);
        String mouth = expireDate.substring(5, 7);
        String dayofmouth = expireDate.substring(8, 10);
        String hour = expireDate.substring(11, 13);
        String minute = expireDate.substring(14, 16);
        String seconds = expireDate.substring(17, expireDate.length());
        calendar.set(Integer.parseInt(year), Integer.parseInt(mouth) - 1, Integer.parseInt(dayofmouth), Integer.parseInt(hour), Integer.parseInt(minute), Integer.parseInt(seconds));
        long timeInMillis = calendar.getTimeInMillis();
        return timeInMillis;
    }

    private void sort(List<TerminalBillMessage> source) {
        int min_index;
        TerminalBillMessage temp = null;
        for (int i = 0; i < source.size() - 1; i++) {
            min_index = i;
            for (int j = i + 1; j < source.size(); j++) {
                if (source.get(min_index).time > source.get(j).time) {
                    min_index = j;
                }
            }
            if (min_index != i) {
                temp = source.get(min_index);
                source.set(min_index, source.get(i));
                source.set(i, temp);
            }
        }
    }
}
